<?php

namespace App\Admin\Controllers\DataView;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Illuminate\Http\Request;

class LogController extends Controller
{
    use ModelForm;

    /**
     * 数据查看
     * @param $table
     * @param string $date
     * @param Request $request
     * @return mixed
     */
    public function index($table, $date = '', Request $request)
    {
        $date = $date ?: date('Ym');
        $config = config('admin.database.' . $table);

        return Admin::content(function (Content $content) use ($table, $config, $date) {

            $content->header($config['table_name']);

            $content->description('列表 - ' . $date);

            $dateList = $this->createYearAndMonthSelect($table, $date);

            $content->row((new Box('按年月份进行查询', $dateList))->style('info')->collapsable());

            $columns = $config['columns'];
            $grid = Admin::grid2($config['class'], $date, function (Grid $grid) use ($columns) {
                $grid->id('ID')->sortable();

                foreach ($columns as $key => $value) {
                    $grid->$key($value)->sortable();
                }

                $grid->disableActions();

                $grid->disableCreation();
                $grid->disableBatchDeletion(); //禁用批量操作

                $grid->filter(function ($filter) {
                    $filter->like('receivetime');
                    // $filter->useModal();
                });
            });
            $content->body($grid);
        });
    }

    /**
     * 自定义年月条件查询表单
     * @param $table
     * @param $date
     * @return string
     */
    public function createYearAndMonthSelect($table, $date)
    {
        $y = substr($date, 0, 4);
        $m = substr($date, -2);

        $years = config('admin.database.years');
        $months = config('admin.database.months');
        $y_options = '';
        $m_options = '';
        foreach ($years as $v) {
            $y_options .= '<option ' . ($v === $y ? 'selected' : '') . '>' . $v . '</option>';
        }
        foreach ($months as $v) {
            $m_options .= '<option ' . ($v === $m ? 'selected' : '') . '>' . $v . '</option>';
        }

        return <<<EOF
<div class="row form">
<div class="col-lg-1">
<select id="date_y" class="form-control">{$y_options}</select>
</div>
<div class="col-lg-1">
<select id="date_m" class="form-control">{$m_options}</select>
</div>
<div class="col-lg-1">
<input type="button" class="btn btn-success" value="前往" onclick="logTableWithDate()">
</div>
</div>
<script>
function logTableWithDate() {
    y = document.getElementById('date_y').value;
    m = document.getElementById('date_m').value;
    date = y + m;
    location.href = "/admin/dataView/log/{$table}/" + date;
}
</script>
EOF;
    }
}
